/* eslint-disable indent */
'use strict'

const CryptoJS = require('crypto-js')

// const iv = CryptoJS.enc.Utf8.parse('1234567812345678')

module.exports = {

    // 生成随机数
    random(len) {
        len = len || 32
        const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
        const maxPos = $chars.length
        let pwd = ''
        for (let i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
        }
        return pwd
    },

    // 解密方法
    decrypt(data, key, iv) {
        const dataHexStr = CryptoJS.enc.Hex.parse(data)
        const dataBase64 = CryptoJS.enc.Base64.stringify(dataHexStr)
        const key32 = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(key).toString())
        const iv32 = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(iv).toString())
        const decrypt = CryptoJS.AES.decrypt(dataBase64, key32, { iv: iv32, mode: CryptoJS.mode.CBC })
        try {
            const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
            return decryptedStr.toString()
        } catch (error) {
            console.log('解密失败', error)
            return null
        }
    },

    // 加密方法
    encrypt(data, key, iv) {
        const key32 = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(key).toString())
        const iv32 = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(iv).toString())
        const encrypted = CryptoJS.AES.encrypt(data, key32, { iv: iv32, mode: CryptoJS.mode.CBC })
        const dataBase64 = encrypted.ciphertext.toString()
        return dataBase64
    }

}
